package jiuwu.gqz.audiorecord

import android.os.Environment
import android.util.Log
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import kotlin.math.max

class RecordFileHelper {

    val TAG = "RecordFileHelper-->"

    val cachePath = Environment.getExternalStorageDirectory().absolutePath + "/ChatVoice"

    val fileList = mutableListOf<File>()
    var curFile: File? = null

    init {
        var f = File(cachePath)
        if (!f.exists()) f.mkdirs()
        refreshFileList()
    }

    fun refreshFileList() {
        fileList.clear()
        var dir = File(cachePath)
        fileList.addAll(dir.listFiles())
    }

    //新文件id为目录下最大文件id+1
    //return file path
    fun createFile(): File {
        refreshFileList()
        var maxId = -1
        for (f in fileList) {
            var id = getFileId(f.name)
            if (id > maxId)
                maxId = id
        }
        maxId++
        var file = File(cachePath + "/voice" + maxId)
        if (!file.exists()) {
            file.createNewFile()
            curFile = file
        } else {
            Log.e(TAG, "createFile: failed! file exists")
        }
        return file
    }

    fun getLastFile():File?{

        refreshFileList()
        var maxId = -1
        for (f in fileList) {
            var id = getFileId(f.name)
            if (id > maxId)
                maxId = id
        }
        var file = File(cachePath + "/voice" + maxId)
        if (file.exists()) {
            return file
        }

        return null
    }

    fun getFilePath(fileId: Int): String {
        return ""
    }

    fun getFileId(fileName: String): Int {
        if (fileName.contains("voice", true)) {
            var idStr = fileName.removePrefix("voice")
            var id = idStr.toInt()
            if (id >= 0) return id
        } else Log.e(TAG, "getFileId: failed!")
        return 0
    }



}